<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-09
 * Time: 14:59
 */

namespace app\api\service\room;


use app\api\model\Admin;
use app\api\model\HotelRoom;
use LinCmsTp5\exception\ParameterException;
use think\Db;
use think\Exception;

class CreateRoom
{
    // post的信息
    protected $postArr;

    function __construct($post)
    {
        $this->postArr = $post;
    }

    // 入口文件
    public function create()
    {
        $admin = Admin::with('linUser')->where('lin_user_id',$this->postArr['lin_user_id'])->find();
        if(!$admin) {
            throw new ParameterException([
                'msg' => [
                    'room' => '请先完善酒店基本信息'
                ]
            ]);
        }
        $this->postArr['admin_id'] = $admin['id'];
        $this->postArr['city_id'] = $admin['lin_user']['city_id'];
        $this->postArr['province_id'] = $admin['lin_user']['province_id'];
        $this->postArr['county_id'] = $admin['lin_user']['county_id'];
        //事务开始
        Db::startTrans();
        try{
            // 创建房间信息
            $mode = HotelRoom::create($this->postArr);
            // 图片
            $mode->imgs()->saveAll($this->postArr['imgs']);
            // 基础信息
            $mode->basis()->saveAll($this->postArr['basis']);
            // 标签
            $mode->tag()->saveAll($this->postArr['tag']);
            // 设备与服务
            $mode->facility()->saveAll($this->postArr['facility']);
            // 入住要求
            $mode->claim()->saveAll($this->postArr['claim']);
            //事务结束  开始到结束中间出现错误以后,先执行的添加就不会生成记录
            Db::commit();
            return writeJson(201, [], '添加成功！');
        }
        catch (Exception $ex){
            //回滚事务
            Db::rollback();
            throw $ex;
        }
    }


}